<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Youtu-GraphRAG - Enterprise-level solutions for complex reasoning</title>
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    
    <!-- CDN Dependencies -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios@1.6.2/dist/axios.min.js"></script>
    
    <style>
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: 
                linear-gradient(135deg, #a8c8ec 0%, #e6f3ff 25%, #e6f3ff 75%, #b8d4f0 100%),
                linear-gradient(45deg, #4a90e2 0%, #6b73ff 50%, #9bb5ff 100%);
            background-blend-mode: multiply;
            background-attachment: fixed;
            min-height: 100vh;
            color: rgba(255, 255, 255, 0.95);
            overflow-x: hidden;
            position: relative;
        }

        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: 
                radial-gradient(circle at 20% 80%, rgba(168, 200, 236, 0.3) 0%, transparent 60%),
                radial-gradient(circle at 80% 20%, rgba(182, 212, 240, 0.3) 0%, transparent 60%),
                radial-gradient(circle at 40% 40%, rgba(230, 243, 255, 0.2) 0%, transparent 60%);
            z-index: -1;
            animation: backgroundFloat 25s ease-in-out infinite;
        }

        @keyframes backgroundFloat {
            0%, 100% { transform: translate(0, 0) rotate(0deg) scale(1); }
            25% { transform: translate(20px, -15px) rotate(1deg) scale(1.02); }
            50% { transform: translate(-15px, 20px) rotate(-0.5deg) scale(0.98); }
            75% { transform: translate(15px, 10px) rotate(0.5deg) scale(1.01); }
        }

        @keyframes gradientShift {
            0% { background-position: 0% 50%; }
            25% { background-position: 100% 50%; }
            50% { background-position: 50% 100%; }
            75% { background-position: 50% 0%; }
            100% { background-position: 0% 50%; }
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            text-align: center;
            padding: 35px 20px;
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(10px);
            border-radius: 25px;
            margin-bottom: 30px;
            border: 2px solid rgba(255, 255, 255, 0.25);
            box-shadow: 
                0 15px 45px rgba(102, 126, 234, 0.15),
                0 5px 15px rgba(245, 87, 108, 0.1),
                inset 0 1px 0 rgba(255, 255, 255, 0.4);
            position: relative;
            overflow: hidden;
        }

        .header::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.05), transparent);
            animation: headerShine 6s ease-in-out infinite;
        }

        @keyframes headerShine {
            0% { transform: translateX(-100%) translateY(-100%) rotate(45deg); }
            50% { transform: translateX(100%) translateY(100%) rotate(45deg); }
            100% { transform: translateX(-100%) translateY(-100%) rotate(45deg); }
        }

        .logo-container {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 20px;
            margin-bottom: 15px;
            position: relative;
            z-index: 2;
        }

        .logo-image {
            height: 120px;
            width: auto;
            max-width: 180px;
            /* border-radius: 15px;
            border: 3px solid rgba(255, 255, 255, 0.4); */
            /* box-shadow: 
                0 4px 20px rgba(0, 0, 0, 0.2),
                0 0 30px rgba(255, 255, 255, 0.1); */
            animation: logoFloat 4s ease-in-out infinite;
            object-fit: contain;
        }

        @keyframes logoFloat {
            0%, 100% { transform: translateY(0px) rotate(0deg); }
            50% { transform: translateY(-8px) rotate(2deg); }
        }

        .logo {
            font-size: 2.8em;
            font-weight: 700;
            color: #ffffff;
            margin: 0;
            text-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
        }

        @keyframes gradientShift {
            0%, 100% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
        }

        .subtitle {
            color: #ffffff;
            font-size: 1.2em;
            font-weight: 400;
            font-style: italic;
            position: relative;
            z-index: 2;
            text-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
        }

        .card {
            background: rgba(255, 255, 255, 0.2);
            backdrop-filter: blur(8px);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 25px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            box-shadow: 
                0 8px 32px rgba(0, 0, 0, 0.2),
                inset 0 1px 0 rgba(255, 255, 255, 0.4);
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
        }

        .card::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
            transition: left 0.6s;
        }

        .card:hover {
            transform: translateY(-8px) scale(1.02);
            box-shadow: 
                0 20px 40px rgba(0, 0, 0, 0.2),
                inset 0 1px 0 rgba(255, 255, 255, 0.4);
            border-color: rgba(255, 255, 255, 0.4);
        }

        .card:hover::before {
            left: 100%;
        }

        .card h2 {
            margin-bottom: 20px;
            color: rgba(255, 255, 255, 0.95);
            font-weight: 600;
        }

        .tabs {
            display: flex;
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(8px);
            border-radius: 20px;
            padding: 6px;
            margin-bottom: 30px;
            border: 2px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
        }

        .tab {
            flex: 1;
            padding: 16px 24px;
            text-align: center;
            border-radius: 16px;
            cursor: pointer;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            font-weight: 600;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            color: rgba(255, 255, 255, 0.7);
            position: relative;
            overflow: hidden;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .tab::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
            transition: left 0.6s;
        }

        .tab:hover::before {
            left: 100%;
        }

        .tab.active {
            background: linear-gradient(135deg, rgba(255, 107, 107, 0.3) 0%, rgba(78, 205, 196, 0.3) 50%, rgba(69, 183, 209, 0.3) 100%);
            color: rgba(255, 255, 255, 0.95);
            box-shadow: 
                0 4px 20px rgba(0, 0, 0, 0.2),
                inset 0 1px 0 rgba(255, 255, 255, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.3);
            transform: scale(1.02);
        }

        .tab:hover:not(.active) {
            background: rgba(255, 255, 255, 0.12);
            color: rgba(255, 255, 255, 0.9);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .upload-area {
            border: 3px dashed rgba(255, 182, 193, 0.4);
            border-radius: 20px;
            padding: 50px;
            text-align: center;
            cursor: pointer;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            background: rgba(255, 255, 255, 0.05);
            backdrop-filter: blur(10px);
            position: relative;
            overflow: hidden;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }

        .upload-area::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: linear-gradient(45deg, transparent, rgba(255, 182, 193, 0.1), transparent);
            transition: transform 0.6s;
            transform: translateX(-100%) translateY(-100%) rotate(45deg);
        }

        .upload-area:hover::before {
            transform: translateX(100%) translateY(100%) rotate(45deg);
        }

        .upload-area:hover {
            border-color: rgba(255, 182, 193, 0.8);
            background: rgba(255, 182, 193, 0.1);
            transform: translateY(-4px);
            box-shadow: 
                0 10px 30px rgba(0, 0, 0, 0.2),
                0 0 20px rgba(255, 182, 193, 0.3);
        }

        .upload-area.dragover {
            border-color: rgba(78, 205, 196, 0.8);
            background: rgba(78, 205, 196, 0.15);
            transform: scale(1.03) translateY(-4px);
            box-shadow: 
                0 15px 40px rgba(0, 0, 0, 0.3),
                0 0 30px rgba(78, 205, 196, 0.4);
        }

        .upload-icon {
            font-size: 64px;
            margin-bottom: 20px;
            background: linear-gradient(45deg, #6b73ff, #9bb5ff, #a8c8ec);
            background-clip: text;
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            position: relative;
            z-index: 2;
            animation: iconPulse 2s ease-in-out infinite;
        }

        @keyframes iconPulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.1); }
        }

        .btn {
            color: white;
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.8) 0%, rgba(118, 75, 162, 0.8) 100%);
            border: 2px solid rgba(255, 255, 255, 0.3);
            padding: 12px 24px;
            border-radius: 25px;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            margin: 4px 6px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            position: relative;
            overflow: hidden;
            backdrop-filter: blur(10px);
            text-transform: uppercase;
            letter-spacing: 1px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        }

        .btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.6s;
        }

        .btn:hover::before {
            left: 100%;
        }

        .btn-primary {
            background: linear-gradient(135deg, #4a90e2 0%, #6b73ff 50%, #9bb5ff 100%);
            background-size: 200% 200%;
            animation: gradientMove 3s ease infinite;
        }

        .btn-secondary {
            background: linear-gradient(135deg, #a8c8ec 0%, #b8d4f0 50%, #e6f3ff 100%);
            background-size: 200% 200%;
            animation: gradientMove 4s ease infinite;
        }

        .btn-danger {
            background: linear-gradient(135deg, #6b73ff 0%, #4a90e2 50%, #9bb5ff 100%);
            background-size: 200% 200%;
            animation: gradientMove 3.5s ease infinite;
        }

        @keyframes gradientMove {
            0%, 100% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
        }

        .btn:hover {
            transform: translateY(-4px) scale(1.05);
            box-shadow: 
                0 8px 25px rgba(0, 0, 0, 0.3),
                0 0 20px rgba(255, 255, 255, 0.1);
            border-color: rgba(255, 255, 255, 0.5);
            animation-duration: 1.5s;
        }

        .btn:active {
            transform: translateY(-2px) scale(1.02);
        }

        .btn-primary:hover {
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary:hover {
            box-shadow: 0 4px 15px rgba(78, 205, 196, 0.4);
        }

        .btn-danger:hover {
            box-shadow: 0 4px 15px rgba(255, 107, 107, 0.4);
        }

        .dataset-actions {
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .btn-secondary {
            background: rgba(255, 255, 255, 0.1);
            box-shadow: none;
        }

        .input-group {
            margin-bottom: 25px;
        }

        .input-group label {
            display: block;
            margin-bottom: 12px;
            color: rgba(255, 255, 255, 0.95);
            font-weight: 600;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            font-size: 16px;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        }

        .input, .textarea, .select {
            width: 100%;
            padding: 16px 20px;
            border: 2px solid rgba(255, 255, 255, 0.18);
            border-radius: 15px;
            background: rgba(25, 25, 25, 0.65); /* darker background */
            backdrop-filter: blur(4px);
            color: rgba(255,255,255,0.92);
            font-size: 15px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            box-shadow:
                0 4px 18px rgba(0, 0, 0, 0.35),
                inset 0 1px 0 rgba(255, 255, 255, 0.06);
        }

        .input:focus, .textarea:focus, .select:focus {
            outline: none;
            border-color: rgba(120, 200, 255, 0.55);
            background: rgba(35, 35, 35, 0.85);
            backdrop-filter: blur(3px);
            box-shadow:
                0 0 0 3px rgba(120, 200, 255, 0.15),
                0 8px 28px rgba(0, 0, 0, 0.45),
                inset 0 1px 0 rgba(255, 255, 255, 0.08);
            transform: translateY(-2px);
        }

        .input::placeholder, .textarea::placeholder {
            color: rgba(255, 255, 255, 0.6);
            font-style: italic;
        }

        .textarea {
            resize: vertical;
            min-height: 120px;
        }

        .progress-bar {
            width: 100%;
            height: 6px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 3px;
            overflow: hidden;
            margin: 16px 0;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(45deg, #6b73ff, #9bb5ff);
            transition: width 0.3s ease;
            width: 0%;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 16px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-ready {
            /* Darker, more saturated green */
            background: rgba(20, 138, 46, 0.22);
            color: #148A2E;
            border: 1px solid rgba(20, 138, 46, 0.55);
        }

        .status-processing {
            background: rgba(250, 173, 20, 0.2);
            color: #faad14;
            border: 1px solid rgba(250, 173, 20, 0.4);
        }

        .status-error {
            background: rgba(255, 77, 79, 0.2);
            color: #ff4d4f;
            border: 1px solid rgba(255, 77, 79, 0.4);
        }

        /* Quick Actions uniform layout */
        .quick-actions {
            display: flex;
            flex-wrap: nowrap;
            gap: 16px;
            width: 100%;
        }
        .quick-actions .btn {
            flex: 1 1 0;
            display: flex;
            align-items: center;
            justify-content: center;
            white-space: nowrap;
            font-size: 14px;
            min-height: 48px;
        }
        @media (max-width: 900px) {
            .quick-actions { flex-wrap: wrap; }
            .quick-actions .btn { flex: 1 1 calc(50% - 16px); }
        }

        .chart-container {
            height: 500px;
            background: linear-gradient(140deg, rgba(18,24,36,0.92) 0%, rgba(30,42,60,0.88) 60%, rgba(42,58,82,0.85) 100%);
            backdrop-filter: blur(6px);
            border-radius: 20px;
            margin: 25px 0;
            border: 2px solid rgba(255, 255, 255, 0.08);
            box-shadow:
                0 10px 34px -4px rgba(0,0,0,0.55),
                0 2px 0 rgba(255,255,255,0.08) inset,
                0 0 22px -6px rgba(107,115,255,0.4);
            position: relative;
            overflow: hidden;
        }

        .chart-container::before {
            content: '';
            position: absolute;
            top: -2px;
            left: -2px;
            right: -2px;
            bottom: -2px;
            background: linear-gradient(90deg, 
                rgba(79, 172, 254, 0.6), 
                rgba(102, 126, 234, 0.4), 
                rgba(118, 75, 162, 0.5), 
                rgba(156, 39, 176, 0.6));
            border-radius: 20px;
            z-index: -1;
            animation: borderGlow 12s ease-in-out infinite;
        }

        @keyframes borderGlow {
            0%, 100% { opacity: 0.5; }
            50% { opacity: 0.8; }
        }

        .retrieval-details {
            /* High contrast container */
            background: linear-gradient(145deg, rgba(15,22,33,0.92) 0%, rgba(30,42,60,0.88) 100%);
            border-radius: 14px;
            padding: 24px 26px 20px;
            margin: 28px 0 24px;
            border: 1px solid rgba(255, 255, 255, 0.12);
            box-shadow: 0 10px 28px -6px rgba(0,0,0,0.55), 0 2px 0 rgba(255,255,255,0.06) inset;
            position: relative;
            overflow: hidden;
        }

        .retrieval-details::before {
            content: '';
            position: absolute;
            inset: 0;
            background: radial-gradient(circle at 12% 18%, rgba(107,115,255,0.18), transparent 60%),
                        radial-gradient(circle at 88% 82%, rgba(155,181,255,0.16), transparent 65%);
            pointer-events: none;
            mix-blend-mode: screen;
        }

        .retrieval-summary h4,
        .subquestions-section h4,
        .triples-section h4 {
            color: rgba(255, 255, 255, 0.95);
            margin-bottom: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
            padding-bottom: 8px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .stat-item {
            background: rgba(255, 255, 255, 0.1);
            padding: 12px;
            border-radius: 6px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .stat-label {
            color: rgba(255, 255, 255, 0.8);
            font-size: 14px;
        }

        .stat-value {
            color: #6b73ff;
            font-weight: bold;
            font-size: 16px;
        }

        .subquestion-item {
            /* Higher-contrast panel for readability */
            background: linear-gradient(135deg, rgba(18,25,38,0.88) 0%, rgba(34,45,65,0.82) 100%);
            backdrop-filter: blur(6px);
            border-radius: 10px;
            padding: 16px 18px 14px;
            margin-bottom: 16px;
            border: 1px solid rgba(255,255,255,0.12);
            border-left: 5px solid #6b73ff;
            box-shadow: 0 4px 14px rgba(0,0,0,0.45), 0 1px 0 rgba(255,255,255,0.08) inset;
            position: relative;
            overflow: hidden;
            transition: background 0.3s ease, transform 0.25s ease, box-shadow 0.3s ease;
        }

        .subquestion-item::before {
            content: '';
            position: absolute;
            top: 0; left: 0; right: 0; bottom: 0;
            background: radial-gradient(circle at 15% 20%, rgba(107,115,255,0.20), transparent 60%),
                        radial-gradient(circle at 85% 80%, rgba(155,181,255,0.18), transparent 65%);
            opacity: 0.9;
            pointer-events: none;
        }

        .subquestion-item:hover {
            background: linear-gradient(135deg, rgba(25,35,50,0.92) 0%, rgba(46,60,85,0.86) 100%);
            transform: translateY(-3px);
            box-shadow: 0 8px 22px rgba(0,0,0,0.55), 0 2px 0 rgba(255,255,255,0.08) inset;
        }

        .subquestion-header {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .subquestion-number {
            background: #9bb5ff;
            color: white;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
            margin-right: 12px;
        }

        .subquestion-text {
            color: rgba(255, 255, 255, 0.9);
            font-weight: 500;
        }

        .subquestion-stats {
            display: flex;
            gap: 15px;
            margin-bottom: 10px;
            font-size: 13px;
        }

        .subquestion-stats span {
            background: rgba(255, 255, 255, 0.1);
            padding: 4px 8px;
            border-radius: 4px;
            color: rgba(255, 255, 255, 0.8);
        }

        .triples-preview {
            margin-top: 10px;
            background: rgba(0, 0, 0, 0.2);
            padding: 10px;
            border-radius: 6px;
        }

        .triples-preview strong {
            color: rgba(255, 255, 255, 0.9);
            display: block;
            margin-bottom: 8px;
        }

        .triples-preview ul {
            margin: 0;
            padding-left: 20px;
        }

        .triples-preview li {
            color: rgba(255, 255, 255, 0.8);
            margin-bottom: 4px;
            font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
            font-size: 13px;
        }

        .more-indicator {
            color: #6b73ff;
            font-style: italic;
            font-size: 12px;
        }

        .triple-item {
            display: flex;
            align-items: flex-start;
            padding: 8px 12px;
            margin-bottom: 8px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 6px;
            border-left: 3px solid #6b73ff;
        }

        .triple-number {
            background: #6b73ff;
            color: white;
            min-width: 20px;
            height: 20px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 11px;
            font-weight: bold;
            margin-right: 12px;
            margin-top: 2px;
        }

        .triple-content {
            color: rgba(255, 255, 255, 0.85);
            font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
            font-size: 13px;
            line-height: 1.4;
        }

        .more-triples {
            text-align: center;
            color: #6b73ff;
            font-style: italic;
            padding: 10px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 6px;
            margin-top: 10px;
        }

        .no-data {
            color: rgba(255, 255, 255, 0.6);
            font-style: italic;
            text-align: center;
            padding: 20px;
        }

        .triples-chart-container {
            margin: 15px 0;
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 8px;
            background: rgba(255, 255, 255, 0.02);
            overflow: hidden;
        }

        .triples-summary {
            text-align: center;
            padding: 10px;
            background: rgba(255, 255, 255, 0.05);
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            color: rgba(255, 255, 255, 0.8);
        }

        .triples-summary strong {
            color: #6b73ff;
            font-size: 16px;
        }

        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin: 20px 0;
        }

        .stat-card {
            text-align: center;
            padding: 20px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 12px;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .stat-number {
            font-size: 2em;
            font-weight: 700;
            color: #6b73ff;
            margin-bottom: 8px;
        }

        .stat-label {
            color: rgba(255, 255, 255, 0.7);
        }

        .loading {
            display: none;
            text-align: center;
            padding: 40px;
        }

        .loading.show {
            display: block;
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-top: 3px solid white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 16px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .message {
            padding: 12px 16px;
            border-radius: 8px;
            margin: 16px 0;
        }

        .message.success {
            background: rgba(82, 196, 26, 0.2);
            border: 1px solid rgba(82, 196, 26, 0.4);
            color: #52c41a;
        }

        .message.error {
            background: rgba(255, 77, 79, 0.2);
            border: 1px solid rgba(255, 77, 79, 0.4);
            color: #ff4d4f;
        }

        .message.info {
            /* Bright green theme for info messages */
            background: rgba(82, 242, 107, 0.18);
            border: 1px solid rgba(82, 242, 107, 0.55);
            color: #52f26b; /* bright green text */
            text-shadow: 0 0 2px rgba(82,242,107,0.4);
        }

        .answer-content {
            background: linear-gradient(120deg, rgba(20,28,42,0.94) 0%, rgba(34,46,66,0.9) 100%);
            border-left: 6px solid #6b73ff;
            padding: 22px 26px 24px;
            border-radius: 14px;
            margin: 26px 0 20px;
            line-height: 1.66;
            border: 1px solid rgba(255,255,255,0.12);
            box-shadow: 0 8px 24px -4px rgba(0,0,0,0.55), 0 1px 0 rgba(255,255,255,0.08) inset;
            position: relative;
            overflow: hidden;
        }

        .answer-content::before {
            content: '';
            position: absolute;
            inset: 0;
            background: radial-gradient(circle at 18% 22%, rgba(107,115,255,0.22), transparent 55%),
                        radial-gradient(circle at 82% 78%, rgba(155,181,255,0.18), transparent 60%);
            pointer-events: none;
            opacity: 0.9;
        }

        .file-list {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 8px;
            padding: 16px;
            margin: 16px 0;
            max-height: 200px;
            overflow-y: auto;
        }

        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .file-item:last-child {
            border-bottom: none;
        }

        .hidden {
            display: none !important;
        }

        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
            
            .tabs {
                flex-direction: column;
            }
            
            .grid {
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <div class="logo-container">
                <img src="/assets/logo.png" alt="Youtu-GraphRAG Logo" class="logo-image">
                <div class="logo">Youtu-GraphRAG</div>
            </div>
            <div class="subtitle">✨ Vertically Unified Agents for Graph Retrieval-Augmented Complex Reasoning ✨</div>
        </div>

        <!-- Navigation Tabs -->
        <div class="tabs">
            <div class="tab active" onclick="switchTab('dashboard')">📊 Dashboard</div>
            <div class="tab" onclick="switchTab('upload')">📤 Data Upload</div>
            <div class="tab" onclick="switchTab('graph')">🕸️ Graph Visualization</div>
            <div class="tab" onclick="switchTab('qa')">🤖 Q&A Interface</div>
        </div>

        <!-- Dashboard Tab -->
        <div id="dashboard" class="tab-content active">
            <div class="card">
                <h2>System Overview</h2>
                <div class="grid">
                    <div class="stat-card">
                        <div class="stat-number" id="stat-datasets">0</div>
                        <div class="stat-label">Datasets</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="stat-graphs">0</div>
                        <div class="stat-label">Constructed Graphs</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="stat-questions">0</div>
                        <div class="stat-label">Questions Asked</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number">
                            <span class="status-badge status-ready">Connected</span>
                        </div>
                        <div class="stat-label">System Status</div>
                    </div>
                </div>
            </div>

            <div class="card">
                <h2>Quick Actions</h2>
                <div class="quick-actions">
                    <button class="btn" onclick="switchTab('upload')">📤 Upload Documents</button>
                    <button class="btn" onclick="switchTab('graph')">🕸️ View Graph</button>
                    <button class="btn" onclick="switchTab('qa')">🤖 Query</button>
                    <button class="btn btn-secondary" onclick="refreshData()">🔄 Refresh</button>
                </div>
            </div>
        </div>

        <!-- Upload Tab -->
        <div id="upload" class="tab-content">
            <div class="card">
                <h2>Upload Documents</h2>
                <div class="upload-area" id="uploadArea">
                    <div class="upload-icon">📁</div>
                    <h3>Drag & Drop Files Here</h3>
                    <p>or click to browse files</p>
                    <p style="font-size: 12px; color: rgba(255,255,255,0.6); margin-top: 12px;">
                        Currently supports: .json
                    </p>
                    <div style="margin-top: 20px; padding: 15px; background: rgba(255,255,255,0.1); border-radius: 10px; text-align: left; font-size: 11px; color: rgba(255,255,255,0.8);">
                        <div style="font-weight: 600; margin-bottom: 8px;">📄 Sample Format (.json):</div>
                        <pre style="margin: 0; font-family: 'JetBrains Mono', 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; background: rgba(0,0,0,0.3); padding: 8px; border-radius: 5px; overflow-x: auto;">
  [
    {
      "title": "Sample doc1",
      "text": "This is a sample document content..."
    },
    {
      "title": "Sample doc2",
      "text": "This is a sample document content..."
    }
  ]
</pre>
                    </div>
                    <input type="file" id="fileInput" multiple accept=".txt,.json,.zip,.md" style="display: none;">
                </div>
                
                <div id="fileList" class="file-list hidden"></div>
                
                <div style="margin-top: 20px;">
                    <button class="btn" id="uploadBtn" disabled onclick="uploadFiles()">Upload Files</button>
                    <button class="btn btn-secondary" onclick="clearFiles()">Clear</button>
                </div>
                
                <div id="uploadProgress" class="hidden">
                    <div class="progress-bar">
                        <div class="progress-fill" id="progressFill"></div>
                    </div>
                    <div id="progressText">Uploading...</div>
                </div>
            </div>

            <div class="card">
                <h2>Available Datasets</h2>
                <div id="datasetsList"></div>
            </div>
        </div>

        <!-- Graph Tab -->
        <div id="graph" class="tab-content">
            <div class="card">
                <h2>Knowledge Tree Visualization</h2>
                <div class="input-group">
                    <label>Dataset:</label>
                    <select class="select" id="graphDataset" onchange="loadGraphData()">
                        <option value="">Select a dataset...</option>
                    </select>
                </div>
                <div class="chart-container" id="graphChart"></div>
            </div>
        </div>

        <!-- Q&A Tab -->
        <div id="qa" class="tab-content">
            <div class="card">
                <h2>Query Panel</h2>
                <div class="input-group">
                    <label>Dataset:</label>
                    <select class="select" id="qaDataset">
                        <option value="">Select a dataset...</option>
                    </select>
                </div>
                <div class="input-group">
                    <label>Query:</label>
                    <!-- <textarea class="textarea" id="questionInput" placeholder="Demo Queston: When was the person who Messi's goals in Copa del Rey compared to get signed by Barcelona?"></textarea> -->
                    <textarea class="textarea" id="questionInput" placeholder="Enter your question here...">When was the person who Messi's goals in Copa del Rey compared to get signed by Barcelona?</textarea>
                </div>
                <button class="btn" onclick="askQuestion()" id="askBtn">Ask Question</button>
                
                <div id="qaLoading" class="loading">
                    <div class="spinner"></div>
                    <div>Processing your question...</div>
                </div>
                
                <div id="answerSection" class="hidden">
                    <h3>Answer:</h3>
                    <div class="answer-content" id="answerContent"></div>
                    
                    <!-- Retrieval Details Container -->
                    <div id="retrievalDetails" class="retrieval-details" style="display: none;"></div>
                    
                    <!-- <h3>Query Analysis:</h3>
                    <div class="chart-container" id="queryChart"></div> -->
                </div>
            </div>
        </div>

        <!-- Messages -->
        <div id="messages"></div>
    </div>

    <script>
        // Global variables
        let selectedFiles = [];
        let datasets = [];
        let currentDataset = null;
        let graphChart = null;
        // let queryChart = null;
        let questionCount = 0;

        // API base URL
        const API_BASE = 'http://localhost:8000';

        // Initialize the app
        document.addEventListener('DOMContentLoaded', function() {
            initializeApp();
            setupEventListeners();
        });

        function initializeApp() {
            refreshData();
            console.log('Youtu-GraphRAG initialized');
        }

        function setupEventListeners() {
            // File upload
            const uploadArea = document.getElementById('uploadArea');
            const fileInput = document.getElementById('fileInput');

            uploadArea.addEventListener('click', () => fileInput.click());
            uploadArea.addEventListener('dragover', handleDragOver);
            uploadArea.addEventListener('dragleave', handleDragLeave);
            uploadArea.addEventListener('drop', handleDrop);
            fileInput.addEventListener('change', handleFileSelect);

            // Question input
            document.getElementById('questionInput').addEventListener('keydown', function(e) {
                if (e.ctrlKey && e.key === 'Enter') {
                    askQuestion();
                }
            });
        }

        function switchTab(tabName) {
            // Update tab buttons
            document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
            event.target.classList.add('active');

            // Update tab content
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
            document.getElementById(tabName).classList.add('active');

            // Load data for specific tabs
            if (tabName === 'upload') {
                loadDatasets();
            } else if (tabName === 'graph') {
                loadDatasetOptions('graphDataset');
            } else if (tabName === 'qa') {
                loadDatasetOptions('qaDataset');
            }
        }

        // File handling
        function handleDragOver(e) {
            e.preventDefault();
            e.currentTarget.classList.add('dragover');
        }

        function handleDragLeave(e) {
            e.preventDefault();
            e.currentTarget.classList.remove('dragover');
        }

        function handleDrop(e) {
            e.preventDefault();
            e.currentTarget.classList.remove('dragover');
            const files = Array.from(e.dataTransfer.files);
            addFiles(files);
        }

        function handleFileSelect(e) {
            const files = Array.from(e.target.files);
            addFiles(files);
        }

        function addFiles(files) {
            selectedFiles = [...selectedFiles, ...files];
            updateFileList();
            document.getElementById('uploadBtn').disabled = selectedFiles.length === 0;
        }

        function updateFileList() {
            const fileList = document.getElementById('fileList');
            if (selectedFiles.length === 0) {
                fileList.classList.add('hidden');
                return;
            }

            fileList.classList.remove('hidden');
            fileList.innerHTML = selectedFiles.map((file, index) => `
                <div class="file-item">
                    <span>📄 ${file.name}</span>
                    <span>${formatFileSize(file.size)} <button onclick="removeFile(${index})" style="background:none;border:none;color:#ff4d4f;cursor:pointer;">✕</button></span>
                </div>
            `).join('');
        }

        function removeFile(index) {
            selectedFiles.splice(index, 1);
            updateFileList();
            document.getElementById('uploadBtn').disabled = selectedFiles.length === 0;
        }

        function clearFiles() {
            selectedFiles = [];
            document.getElementById('fileInput').value = '';
            updateFileList();
            document.getElementById('uploadBtn').disabled = true;
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        async function uploadFiles() {
            if (selectedFiles.length === 0) return;

            const formData = new FormData();
            selectedFiles.forEach(file => formData.append('files', file));
            formData.append('client_id', 'web_client');

            const progressSection = document.getElementById('uploadProgress');
            const progressFill = document.getElementById('progressFill');
            const progressText = document.getElementById('progressText');

            progressSection.classList.remove('hidden');
            document.getElementById('uploadBtn').disabled = true;

            try {
                // Simulate progress
                let progress = 0;
                const progressInterval = setInterval(() => {
                    progress += Math.random() * 20;
                    if (progress > 90) progress = 90;
                    progressFill.style.width = progress + '%';
                    progressText.textContent = `Uploading... ${Math.round(progress)}%`;
                }, 500);

                const response = await axios.post(`${API_BASE}/api/upload`, formData, {
                    headers: { 'Content-Type': 'multipart/form-data' }
                });

                clearInterval(progressInterval);
                progressFill.style.width = '100%';
                progressText.textContent = 'Upload completed!';

                showMessage('Files uploaded successfully!', 'success');
                clearFiles();
                refreshData();

                setTimeout(() => {
                    progressSection.classList.add('hidden');
                }, 2000);

            } catch (error) {
                console.error('Upload failed:', error);
                showMessage('Upload failed: ' + (error.response?.data?.detail || error.message), 'error');
                progressSection.classList.add('hidden');
            } finally {
                document.getElementById('uploadBtn').disabled = false;
            }
        }

        async function refreshData() {
            try {
                await loadDatasets();
                updateStats();
            } catch (error) {
                console.error('Failed to refresh data:', error);
            }
        }

        async function loadDatasets() {
            try {
                const response = await axios.get(`${API_BASE}/api/datasets`);
                datasets = response.data.datasets || [];
                displayDatasets();
                updateStats();
            } catch (error) {
                console.error('Failed to load datasets:', error);
                showMessage('Failed to load datasets', 'error');
            }
        }

        function displayDatasets() {
            const container = document.getElementById('datasetsList');
            if (datasets.length === 0) {
                container.innerHTML = '<p style="color: rgba(255,255,255,0.6);">No datasets available. Upload some files to get started.</p>';
                return;
            }

            container.innerHTML = datasets.map(dataset => `
                <div class="file-item">
                    <div>
                        <strong>${dataset.name}</strong>
                        <span style="color: rgba(255,255,255,0.6);"> (${dataset.type})</span>
                    </div>
                    <div class="dataset-actions">
                        <span class="status-badge status-${dataset.status === 'ready' ? 'ready' : dataset.status === 'constructing' ? 'processing' : 'error'}">
                            ${dataset.status}
                        </span>
                        ${dataset.status === 'needs_construction' ? 
                            `<button class="btn btn-primary" onclick="constructGraph('${dataset.name}')">Construct</button>` : 
                            ''
                        }
                        ${dataset.status === 'ready' ? 
                            `<button class="btn btn-secondary" onclick="reconstructGraph('${dataset.name}')" title="Reconstruct Graph">🔄 Reconstruct</button>` : 
                            ''
                        }
                        ${dataset.type !== 'demo' ? 
                            `<button class="btn btn-danger" onclick="deleteDataset('${dataset.name}')" title="Delete Dataset">🗑️ Delete</button>` : 
                            ''
                        }
                    </div>
                </div>
            `).join('');
        }

        async function constructGraph(datasetName) {
            try {
                showMessage('Starting graph construction...', 'info');
                
                // 建立WebSocket连接来接收实时进展
                const ws = new WebSocket(`ws://${window.location.host}/ws/web_client`);
                let progressMessages = [];
                
                ws.onopen = function() {
                    console.log('WebSocket connected for progress updates');
                };
                
                ws.onmessage = function(event) {
                    try {
                        const data = JSON.parse(event.data);
                        if (data.type === 'progress') {
                            progressMessages.push(data.message);
                            showMessage(`[Construct ${progressMessages.length}] ${data.message}`, 'info');
                        } else if (data.type === 'complete') {
                            showMessage('Graph construction completed!', 'success');
                            ws.close();
                        } else if (data.type === 'error') {
                            showMessage(`Construction error: ${data.message}`, 'error');
                            ws.close();
                        }
                    } catch (e) {
                        console.log('Progress update:', event.data);
                    }
                };
                
                ws.onerror = function(error) {
                    console.log('WebSocket error:', error);
                };
                
                ws.onclose = function() {
                    console.log('WebSocket connection closed');
                };
                
                // Send construct request
                const response = await axios.post(`${API_BASE}/api/construct-graph`, {
                    dataset_name: datasetName,
                    client_id: 'web_client'
                });
                
                // If no WebSocket messages, close after timeout
                setTimeout(() => {
                    if (ws.readyState === WebSocket.OPEN) {
                        ws.close();
                        if (progressMessages.length === 0) {
                            showMessage('Graph construction completed!', 'success');
                        }
                    }
                }, 30000); // 30s timeout
                
                refreshData();
            } catch (error) {
                console.error('Construction failed:', error);
                showMessage('Graph construction failed: ' + (error.response?.data?.detail || error.message), 'error');
            }
        }

        async function reconstructGraph(datasetName) {
            if (!confirm(`Are you sure you want to reconstruct the graph for dataset "${datasetName}"? This will delete the existing graph and cache files.`)) {
                return;
            }
            
            try {
                showMessage('Reconstructing graph...', 'info');
                
                // Open WebSocket for real-time progress
                const ws = new WebSocket(`ws://${window.location.host}/ws/web_client`);
                let progressMessages = [];
                
                ws.onopen = function() {
                    console.log('WebSocket connected for reconstruction progress updates');
                };
                
                ws.onmessage = function(event) {
                    try {
                        const data = JSON.parse(event.data);
                        if (data.type === 'progress') {
                            progressMessages.push(data.message);
                            showMessage(`[Reconstruct ${progressMessages.length}] ${data.message}`, 'info');
                        } else if (data.type === 'complete') {
                            showMessage('Graph reconstruction completed!', 'success');
                            ws.close();
                        } else if (data.type === 'error') {
                            showMessage(`Reconstruction error: ${data.message}`, 'error');
                            ws.close();
                        }
                    } catch (e) {
                        console.log('Reconstruction progress update:', event.data);
                    }
                };
                
                ws.onerror = function(error) {
                    console.log('WebSocket error:', error);
                };
                
                ws.onclose = function() {
                    console.log('WebSocket connection closed');
                };
                
                const response = await axios.post(`${API_BASE}/api/datasets/${datasetName}/reconstruct`, {}, {
                    params: { client_id: 'web_client' }
                });
                
                // If no WebSocket messages, close after timeout
                setTimeout(() => {
                    if (ws.readyState === WebSocket.OPEN) {
                        ws.close();
                        if (progressMessages.length === 0) {
                            showMessage('Graph reconstruction completed!', 'success');
                        }
                    }
                }, 30000); // 30s timeout
                
                refreshData();
            } catch (error) {
                console.error('Reconstruction failed:', error);
                showMessage('Graph reconstruction failed: ' + (error.response?.data?.detail || error.message), 'error');
            }
        }

        async function deleteDataset(datasetName) {
            if (!confirm(`Are you sure you want to delete dataset "${datasetName}"? This action will remove all related files and cannot be undone.`)) {
                return;
            }
            
            try {
                showMessage('Deleting dataset...', 'info');
                const response = await axios.delete(`${API_BASE}/api/datasets/${datasetName}`);
                showMessage(`Dataset "${datasetName}" deleted successfully!`, 'success');
                refreshData();
                
                // If the deleted dataset was selected, clear selections
                const graphDataset = document.getElementById('graphDataset');
                const qaDataset = document.getElementById('qaDataset');
                if (graphDataset.value === datasetName) {
                    graphDataset.value = '';
                }
                if (qaDataset.value === datasetName) {
                    qaDataset.value = '';
                }
            } catch (error) {
                console.error('Deletion failed:', error);
                showMessage('Dataset deletion failed: ' + (error.response?.data?.detail || error.message), 'error');
            }
        }

        function updateStats() {
            document.getElementById('stat-datasets').textContent = datasets.length;
            document.getElementById('stat-graphs').textContent = datasets.filter(d => d.status === 'ready').length;
            document.getElementById('stat-questions').textContent = questionCount;
        }

        function loadDatasetOptions(selectId) {
            const select = document.getElementById(selectId);
            const readyDatasets = datasets.filter(d => d.status === 'ready');
            
            select.innerHTML = '<option value="">Select a dataset...</option>' +
                readyDatasets.map(d => `<option value="${d.name}">${d.name}</option>`).join('');
        }

        async function loadGraphData() {
            const datasetName = document.getElementById('graphDataset').value;
            if (!datasetName) return;

            try {
                const response = await axios.get(`${API_BASE}/api/graph/${datasetName}`);
                const graphData = response.data;
                renderGraph(graphData);
            } catch (error) {
                console.error('Failed to load graph data:', error);
                showMessage('Failed to load graph data', 'error');
            }
        }

        function renderGraph(data) {
            const chartContainer = document.getElementById('graphChart');
            
            if (graphChart) {
                graphChart.dispose();
            }
            
            graphChart = echarts.init(chartContainer);
            
            const option = {
                backgroundColor: 'transparent',
                // title: {
                //     text: 'Knowledge Graph',
                //     left: 'center',
                //     textStyle: { color: 'rgba(255, 255, 255, 0.95)' }
                // },
                tooltip: {
                    trigger: 'item',
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    textStyle: { color: '#ffffff' },
                    formatter: function (params) {
                        if (params.dataType === 'node') {
                            const d = params.data || {};
                            let name = (d.name || '').toString().replace(/\s+/g,' ').trim();
                            if (name.length > 20) name = name.slice(0,20) + '...';
                            const category = d.category || d.type || '';
                            return name ? name : category || 'node';
                        } else if (params.dataType === 'edge') {
                            return params.data && params.data.name ? params.data.name : '';
                        }
                        return '';
                    }
                },
                legend: {
                    type: 'scroll',
                    bottom: 10,
                    textStyle: { color: 'rgba(255, 255, 255, 0.85)' },
                    data: (data.categories && data.categories.map(function(c){return c.name;})) || []
                },
                series: [{
                    type: 'graph',
                    layout: 'force',
                    data: data.nodes || [],
                    links: data.links || [],
                    categories: data.categories || [],
                    roam: true,
                    label: {
                        show: true,
                        color: 'rgba(255, 255, 255, 0.9)',
                        formatter: function(p){
                            const d = p.data || {};
                            let name = (d.name || '').toString().replace(/\s+/g,' ').trim();
                            if (name.length > 20) name = name.slice(0,20) + '...';
                            return name || '';
                        }
                    },
                    force: {
                        repulsion: 1000,
                        gravity: 0.1,
                        edgeLength: 120
                    },
                    lineStyle: {
                        opacity: 0.6,
                        color: 'rgba(255, 255, 255, 0.4)'
                    }
                }]
            };
            
            graphChart.setOption(option);
        }

        async function askQuestion() {
            const datasetName = document.getElementById('qaDataset').value;
            const question = document.getElementById('questionInput').value.trim();

            if (!datasetName || !question) {
                showMessage('Please select a dataset and enter a question', 'error');
                return;
            }

            const loading = document.getElementById('qaLoading');
            const answerSection = document.getElementById('answerSection');
            const askBtn = document.getElementById('askBtn');

            loading.classList.add('show');
            answerSection.classList.add('hidden');
            askBtn.disabled = true;

            try {
                const response = await axios.post(`${API_BASE}/api/ask-question`, {
                    question: question,
                    dataset_name: datasetName,
                    client_id: 'web_client'
                });

                const result = response.data;
                displayAnswer(result);
                questionCount++;
                updateStats();

            } catch (error) {
                console.error('Question failed:', error);
                showMessage('Failed to process question: ' + (error.response?.data?.detail || error.message), 'error');
            } finally {
                loading.classList.remove('show');
                askBtn.disabled = false;
            }
        }

        function displayAnswer(result) {
            console.log('displayAnswer called with result:', result);
            
            document.getElementById('answerContent').textContent = result.answer;
            
            // Display detailed retrieval information
            displayRetrievalDetails(result);
            
            // Render query analysis chart
            // renderQueryChart(result.visualization_data);
            
            document.getElementById('answerSection').classList.remove('hidden');
        }

        function displayRetrievalDetails(result) {
            console.log('displayRetrievalDetails called with:', result);

            // Helper: deduplicate triples array of strings '(s, r, o)' retaining order
            function dedupTriples(arr) {
                if (!Array.isArray(arr)) return [];
                const seen = new Set();
                const out = [];
                for (const t of arr) {
                    if (typeof t !== 'string') continue;
                    const m = t.match(/\(([^,]+),\s*([^,]+),\s*([^\)]+)\)/);
                    if (!m) continue;
                    const key = m.slice(1).map(x => x.trim().toLowerCase()).join('|');
                    if (!seen.has(key)) {
                        seen.add(key);
                        out.push(`(${m[1].trim()}, ${m[2].trim()}, ${m[3].trim()})`);
                    }
                }
                return out;
            }
            
            const detailsContainer = document.getElementById('retrievalDetails');
            if (!detailsContainer) {
                console.error('Retrieval details container not found');
                return;
            }
            
            console.log('Found retrieval details container, showing it');
            
            // Show the container
            detailsContainer.style.display = 'block';

            // Compute total retrieved triples from visible sub-question steps (sum of each step's deduped triples list)
            let subQuestionTriplesTotal = 0;
            if (result.sub_questions && result.sub_questions.length > 0 && Array.isArray(result.reasoning_steps)) {
                for (let i = 0; i < result.sub_questions.length; i++) {
                    const step = result.reasoning_steps[i];
                    if (step && Array.isArray(step.triples)) {
                        subQuestionTriplesTotal += dedupTriples(step.triples).length;
                    } else if (step && typeof step.triples_count === 'number') {
                        // fallback if only count exists
                        subQuestionTriplesTotal += step.triples_count;
                    }
                }
            }
            
            let detailsHtml = `
                <div class="retrieval-summary">
            <h4>🔍 Retrieval Stats</h4>
                    <div class="stats-grid">
                        <div class="stat-item">
                <span class="stat-label">Sub-questions:</span>
                            <span class="stat-value">${result.sub_questions?.length || 0}</span>
                        </div>
                        <div class="stat-item">
                <span class="stat-label">Retrieved Triples (Sum):</span>
                            <span class="stat-value">${subQuestionTriplesTotal}</span>
                        </div>
                        <div class="stat-item">
                <span class="stat-label">Relevant Chunks:</span>
                            <span class="stat-value">${result.retrieved_chunks?.length || 0}</span>
                        </div>
                    </div>
                </div>
                
                <div class="subquestions-section">
            <h4>📝 Question Decomposition</h4>
                    <div class="subquestions-list">
            `;
            
            if (result.sub_questions && result.sub_questions.length > 0) {
                result.sub_questions.forEach((sq, index) => {
                    const step = result.reasoning_steps?.[index] || {};
                    const stepTriples = dedupTriples(step.triples || []);
                    detailsHtml += `
                        <div class="subquestion-item">
                            <div class="subquestion-header">
                                <span class="subquestion-number">${index + 1}</span>
                                <span class="subquestion-text">${sq['sub-question'] || sq.question}</span>
                            </div>
                            <div class="subquestion-stats">
                                <span>Triples: ${stepTriples.length}</span>
                                <span>Chunks: ${step.chunks_count || 0}</span>
                                <span>Time: ${(step.processing_time || 0).toFixed(2)}s</span>
                            </div>
                            ${stepTriples.length > 0 ? `
                                <div class="triples-preview">
                                    <strong>Retrieved Triples:</strong>
                                    <ul>
                                        ${stepTriples.slice(0, 3).map(triple => `<li>${triple}</li>`).join('')}
                                    </ul>
                                    ${stepTriples.length > 3 ? `<span class="more-indicator">...and ${stepTriples.length - 3} more</span>` : ''}
                                </div>
                            ` : ''}
                        </div>
                    `;
                });
            } else {
                detailsHtml += '<p class="no-data">No sub-question data</p>';
            }
            
            detailsHtml += `
                    </div>
                </div>
                
                <div class="triples-section">
                    <h4>🔗 Subgraph Visualization</h4>
                    <div class="triples-chart-container">
                        <div id="triplesChart" class="chart-container" style="height: 400px;"></div>
                    </div>
                    <div class="triples-summary">
                        <p>Retrieved <strong>${result.retrieved_triples?.length || 0}</strong> related triples</p>
                    </div>
                </div>
            `;
            
            detailsHtml += '</div></div>';
            detailsContainer.innerHTML = detailsHtml;
            
            // Render triples chart after setting HTML and ensuring container is visible
            setTimeout(() => {
                console.log('About to render triples chart with:', result.retrieved_triples?.length || 0, 'triples');
                // Make sure the chart container is visible before initializing ECharts
                const chartContainer = document.getElementById('triplesChart');
                if (chartContainer) {
                    chartContainer.style.display = 'block';
                    console.log('Chart container made visible');
                }
                renderTriplesChart(result.retrieved_triples || []);
            }, 200);
        }

        function renderTriplesChart(triples) {
            console.log('renderTriplesChart called with:', triples.length, 'triples');
            console.log('First triple example:', triples[0]);

            // Helper: truncate by words. If more than 3 words, keep first 2 then ellipsis.
            function truncateWords(str){
                if(!str) return '';
                const words = str.split(/\s+/).filter(Boolean);
                if(words.length <= 3) return words.join(' ');
                return words.slice(0,2).join(' ') + '...';
            }
            
            const chartContainer = document.getElementById('triplesChart');
            if (!chartContainer) {
                console.error('Triples chart container not found');
                return;
            }
            
            console.log('Found chart container, container dimensions:', chartContainer.offsetWidth, 'x', chartContainer.offsetHeight);
            
            // Check if ECharts is available
            if (typeof echarts === 'undefined') {
                console.error('ECharts library is not loaded!');
                chartContainer.innerHTML = '<div style="color: red; text-align: center; padding: 50px;">ECharts library not loaded</div>';
                return;
            }
            
            console.log('ECharts library available, version:', echarts.version);
            
            // Dispose existing chart
            if (window.triplesChart && typeof window.triplesChart.dispose === 'function') {
                try {
                    window.triplesChart.dispose();
                    console.log('Previous chart disposed');
                } catch (e) {
                    console.warn('Error disposing previous chart:', e);
                }
            }
            window.triplesChart = null;
            
            try {
                window.triplesChart = echarts.init(chartContainer);
                console.log('ECharts initialized successfully');
            } catch (e) {
                console.error('Error initializing ECharts:', e);
                chartContainer.innerHTML = '<div style="color: red; text-align: center; padding: 50px;">Error initializing ECharts: ' + e.message + '</div>';
                return;
            }
            
            // Parse triples and build graph data
            const nodes = new Map();
            const links = [];
            const categories = new Set();
            
            console.log('Parsing', triples.length, 'triples...');
            
            triples.forEach((tripleStr, index) => {
                // Parse triple format: (subject, relation, object) [score: X.XXX]
                const match = tripleStr.match(/\(([^,]+),\s*([^,]+),\s*([^)]+)\)/);
                if (match) {
                    if (index < 3) {
                        console.log(`Triple ${index + 1} parsed successfully:`, match.slice(1));
                    }
                    let [, subject, relation, object] = match;
                    
                    // Clean up entity names and extract schema types
                    subject = subject.trim();
                    relation = relation.trim();
                    object = object.trim();
                    
                    // Extract schema type if present
                    const subjectType = extractSchemaType(subject) || 'entity';
                    const objectType = extractSchemaType(object) || 'entity';
                    
                    // Clean entity names
                    subject = cleanEntityName(subject);
                    object = cleanEntityName(object);
                    
                    // Add nodes
                    if (!nodes.has(subject)) {
                        nodes.set(subject, {
                            id: subject,
                            name: truncateWords(subject),
                            category: subjectType,
                            symbolSize: Math.min(30 + subject.length * 0.5, 50),
                            itemStyle: { color: getCategoryColor(subjectType) },
                            rawName: subject
                        });
                        categories.add(subjectType);
                    }
                    
                    if (!nodes.has(object)) {
                        nodes.set(object, {
                            id: object,
                            name: truncateWords(object),
                            category: objectType,
                            symbolSize: Math.min(30 + object.length * 0.5, 50),
                            itemStyle: { color: getCategoryColor(objectType) },
                            rawName: object
                        });
                        categories.add(objectType);
                    }
                    
                    // Add link with truncated display name and rawName preserved
                    links.push({
                        source: subject,
                        target: object,
                        name: truncateWords(relation),
                        rawName: relation,
                        lineStyle: { 
                            color: '#6b73ff',
                            width: 2
                        }
                    });
                }
            });
            
            const nodesList = Array.from(nodes.values());
            const categoriesList = Array.from(categories).map(cat => ({
                name: cat,
                itemStyle: { color: getCategoryColor(cat) }
            }));
            
            const option = {
                backgroundColor: 'transparent',
                // title: {
                //     text: '检索三元组知识图谱',
                //     left: 'center',
                //     top: 10,
                //     textStyle: { 
                //         color: 'rgba(255, 255, 255, 0.95)',
                //         fontSize: 16
                //     }
                // },
                tooltip: {
                    trigger: 'item',
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    textStyle: { color: '#ffffff' },
                    formatter: function(params) {
                        if (params.dataType === 'node') {
                            const rawFull = (params.data.rawName || params.data.id || '').toString().replace(/\s+/g,' ').trim();
                            return `<strong>${rawFull}</strong><br/>Type: ${params.data.category}`;
                        } else if (params.dataType === 'edge') {
                            const fullRel = (params.data.rawName || params.data.name || '').toString().replace(/\s+/g,' ').trim();
                            return `<strong>${fullRel}</strong><br/>${params.data.source} → ${params.data.target}`;
                        }
                        return '';
                    }
                },
                legend: {
                    type: 'scroll',
                    bottom: 10,
                    textStyle: { color: 'rgba(255, 255, 255, 0.85)' },
                    data: categoriesList.map(c => c.name)
                },
                series: [{
                    type: 'graph',
                    layout: 'force',
                    data: nodesList,
                    links: links,
                    categories: categoriesList,
                    roam: true,
                    focusNodeAdjacency: true,
                    label: {
                        show: true,
                        position: 'right',
                        color: 'rgba(255, 255, 255, 0.9)',
                        fontSize: 10,
                        formatter: function(p){
                            let name = (p.data && (p.data.rawName || p.data.name || p.data.id) || '').toString().replace(/\s+/g,' ').trim();
                            return truncateWords(name);
                        }
                    },
                    force: {
                        repulsion: 1000,
                        gravity: 0.1,
                        edgeLength: [100, 200],
                        layoutAnimation: true
                    },
                    lineStyle: {
                        opacity: 0.8,
                        curveness: 0.1
                    },
                    edgeLabel: {
                        show: true,
                        color: 'rgba(255,255,255,0.75)',
                        fontSize: 10,
                        formatter: function(p){
                            return truncateWords(p.data && (p.data.rawName || p.data.name) || '');
                        }
                    },
                    emphasis: {
                        focus: 'adjacency',
                        lineStyle: {
                            width: 4
                        }
                    }
                }]
            };
            
            console.log('Setting chart option with:', nodesList.length, 'nodes and', links.length, 'links');
            
            if (nodesList.length === 0) {
                console.warn('No nodes to display, showing empty message');
                chartContainer.innerHTML = '<div style="color: #ffb347; text-align: center; padding: 50px;">No entity relationships found</div>';
                return;
            }
            
            try {
                window.triplesChart.setOption(option);
                console.log('Chart option set successfully');
                
                // Ensure chart is properly sized
                setTimeout(() => {
                    if (window.triplesChart && typeof window.triplesChart.resize === 'function') {
                        try {
                            window.triplesChart.resize();
                            console.log('Chart resized');
                        } catch (e) {
                            console.warn('Error resizing chart:', e);
                        }
                    }
                }, 100);
                
                console.log('Triples chart rendered successfully!');
            } catch (e) {
                console.error('Error setting chart option:', e);
                chartContainer.innerHTML = '<div style="color: red; text-align: center; padding: 50px;">Chart rendering error: ' + e.message + '</div>';
            }
        }
        
        function extractSchemaType(entityStr) {
            const match = entityStr.match(/\[schema_type:\s*([^\]]+)\]/);
            return match ? match[1].trim() : null;
        }
        
        function cleanEntityName(entityStr) {
            return entityStr.replace(/\s*\[schema_type:[^\]]+\]/g, '').trim();
        }
        
        function getCategoryColor(category) {
            const colors = {
                'person': '#6b73ff',
                'organization': '#9bb5ff', 
                'location': '#a8c8ec',
                'event': '#b8d4f0',
                'object': '#e6f3ff',
                'concept': '#4a90e2',
                'attribute': '#6b73ff',
                'entity': '#9bb5ff'
            };
            return colors[category] || '#9bb5ff';
        }

        function renderQueryChart(data) {
            const chartContainer = document.getElementById('queryChart');
            
            if (queryChart) {
                queryChart.dispose();
            }
            
            queryChart = echarts.init(chartContainer);
            
            const option = {
                backgroundColor: 'transparent',
                title: {
                    text: 'Query Decomposition',
                    left: 'center',
                    textStyle: { color: 'rgba(255, 255, 255, 0.95)' }
                },
                tooltip: {
                    trigger: 'item',
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    textStyle: { color: '#ffffff' }
                },
                series: [{
                    type: 'graph',
                    layout: 'force',
                    data: data?.subqueries?.nodes || [
                        {id: 'q1', name: 'Original Question', category: 'question', symbolSize: 40},
                        {id: 'sq1', name: 'Sub-question 1', category: 'sub_question', symbolSize: 30},
                        {id: 'sq2', name: 'Sub-question 2', category: 'sub_question', symbolSize: 30}
                    ],
                    links: data?.subqueries?.links || [
                        {source: 'q1', target: 'sq1'},
                        {source: 'q1', target: 'sq2'}
                    ],
                    categories: data?.subqueries?.categories || [
                        {name: 'question', itemStyle: {color: '#6b73ff'}},
                        {name: 'sub_question', itemStyle: {color: '#9bb5ff'}}
                    ],
                    roam: true,
                    label: {
                        show: true,
                        color: 'rgba(255, 255, 255, 0.9)'
                    },
                    force: {
                        repulsion: 800,
                        gravity: 0.1
                    },
                    lineStyle: {
                        opacity: 0.6,
                        color: 'rgba(255, 255, 255, 0.4)'
                    }
                }]
            };
            
            queryChart.setOption(option);
        }

        function showMessage(text, type = 'info') {
            const messages = document.getElementById('messages');
            const message = document.createElement('div');
            message.className = `message ${type}`;
            message.textContent = text;
            
            messages.appendChild(message);
            
            setTimeout(() => {
                message.remove();
            }, 5000);
        }

        // Initialize on load
        refreshData();
    </script>
</body>
</html>
